package services

import (
	"lwa-go/mysql"
	"strings"
	"sync"
)

type ChapterService struct {
}

func (c ChapterService) fixErrorStringRow(chapterId int, content, errorString, replaceString string) {
	newContent := strings.ReplaceAll(content, errorString, replaceString)
	mysql.UpdateChapterContent(chapterId, newContent)
}

func (c ChapterService) FixErrorStringRows(novelId int, errorString, replaceString string) {
	chapters := mysql.SelectChapterFromNovel(novelId)
	chapterNum := len(chapters)
	wg := sync.WaitGroup{}
	wg.Add(chapterNum)
	for i := 0; i < chapterNum; i++ {
		chapter := chapters[i]
		go func() {
			defer wg.Done()
			c.fixErrorStringRow(chapter.Id, chapter.Content, errorString, replaceString)
		}()
	}
	wg.Wait()
}

func (c ChapterService) ResetOrderNum(novelId int) {
	chapters := mysql.SelectChapersOrderNum(novelId)
	wg := sync.WaitGroup{}
	chapterNum := len(chapters)
	wg.Add(chapterNum)
	for i := 0; i < chapterNum; i++ {
		chapterId := chapters[i].Id
		go func(i int) {
			defer wg.Done()
			c.resetChapterOrderNum(novelId, chapterId, i+1)
		}(i)
	}
	wg.Wait()
}

func (c ChapterService) resetChapterOrderNum(novelId, chapterId, orderNum int) {
	mysql.SetChapterOrderNum(novelId, chapterId, orderNum)
}
